package com.lncd.backend.service.impl;

import com.lncd.backend.dto.UserDTO;
import com.lncd.backend.model.User;
import com.lncd.backend.repository.UserRepository;
import com.lncd.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public UserDTO register(UserDTO userDTO) {
        // 检查用户名和手机号是否已存在
        if (userRepository.existsByUsername(userDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        if (userRepository.existsByPhone(userDTO.getPhone())) {
            throw new RuntimeException("手机号已存在");
        }

        User user = UserDTO.toEntity(userDTO);
        user = userRepository.save(user);
        return UserDTO.fromEntity(user);
    }

    @Override
    public UserDTO login(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }

        return UserDTO.fromEntity(user);
    }

    @Override
    public UserDTO getUserById(Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return UserDTO.fromEntity(user);
    }

    @Override
    @Transactional
    public UserDTO updateUser(Long id, UserDTO userDTO) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 更新基本信息
        if (userDTO.getUsername() != null && !userDTO.getUsername().equals(user.getUsername())) {
            if (userRepository.existsByUsername(userDTO.getUsername())) {
                throw new RuntimeException("用户名已存在");
            }
            user.setUsername(userDTO.getUsername());
        }

        if (userDTO.getPhone() != null && !userDTO.getPhone().equals(user.getPhone())) {
            if (userRepository.existsByPhone(userDTO.getPhone())) {
                throw new RuntimeException("手机号已存在");
            }
            user.setPhone(userDTO.getPhone());
        }

        if (userDTO.getPassword() != null) {
            user.setPassword(userDTO.getPassword());
        }

        if (userDTO.getUserType() != null) {
            user.setUserType(userDTO.getUserType());
        }

        if (userDTO.getEmergencyContact() != null) {
            user.setEmergencyContact(userDTO.getEmergencyContact());
        }

        user = userRepository.save(user);
        return UserDTO.fromEntity(user);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        if (!userRepository.existsById(id)) {
            throw new RuntimeException("用户不存在");
        }
        userRepository.deleteById(id);
    }

    @Override
    public List<UserDTO> getAllUsers() {
        return userRepository.findAll().stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public UserDTO addRelation(Long userId, Long relatedUserId) {
        if (userId.equals(relatedUserId)) {
            throw new RuntimeException("不能关联自己");
        }

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        User relatedUser = userRepository.findById(relatedUserId)
                .orElseThrow(() -> new RuntimeException("关联用户不存在"));

        // 检查是否已经关联
        if (user.getRelatedUsers().contains(relatedUser)) {
            throw new RuntimeException("已经关联该用户");
        }

        // 添加双向关联
        user.getRelatedUsers().add(relatedUser);
        relatedUser.getRelatedUsers().add(user);
        
        // 保存双方关系
        userRepository.saveAndFlush(user);
        userRepository.saveAndFlush(relatedUser);
        
        return UserDTO.fromEntity(user);
    }

    @Override
    @Transactional
    public UserDTO removeRelation(Long userId, Long relatedUserId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        User relatedUser = userRepository.findById(relatedUserId)
                .orElseThrow(() -> new RuntimeException("关联用户不存在"));

        // 检查是否已经关联
        if (!user.getRelatedUsers().contains(relatedUser)) {
            throw new RuntimeException("未关联该用户");
        }

        // 移除双向关联
        user.getRelatedUsers().remove(relatedUser);
        relatedUser.getRelatedUsers().remove(user);
        
        // 保存双方关系
        userRepository.saveAndFlush(user);
        userRepository.saveAndFlush(relatedUser);
        
        return UserDTO.fromEntity(user);
    }

    @Override
    public List<UserDTO> getRelatedUsers(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return user.getRelatedUsers().stream()
                .map(UserDTO::fromEntity)
                .collect(Collectors.toList());
    }
} 